Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
Login function saving token to localStorage as [Object][Object]

I am trying to login to my user account which is saved on database and attach a token to that username with 'jwt-token'.

router.post('/users/login', (req, res) => {
  User.authenticate()(req.body.username, req.body.password, (err, user) => {
    if (err) { console.log(err) }
    res.json(user ? jwt.sign({ id: user._id }, process.env.SECRET) : null)
  })
})

However when i login to the account, the token is being saved, as [Object][Object] in the local storage via this function here,

  // when a user clicks login
  const handleLogin = (event) => {
    event.preventDefault();
    axios.post('/api/users/login', {
      username: userState.username,
      password: userState.password
    }).then(token => {
      console.log(token)
      setLoginState(true)
      localStorage.setItem('username', userState.username)
      localStorage.setItem('token', token)

    }).catch(err => { console.log(err) })

What is the reason the token is saving as an object? is it not properly being created by my route? or am I not calling it correctly in my .then call? any insight would be appreciated. Still trying to learn as much as i can on backend work and seem to hit problems at every step.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

We have to stringify while storing objects in storage and parse the stored objects while retrieving.

// Put the object into storage
localStorage.setItem('username', JSON.stringify(username));

// Retrieve the object from storage
var retrievedUsername= localStorage.getItem('username');
console.log('retrievedUsername: ', JSON.parse(retrievedUsername));
about 4 years ago · Juan Pablo Isaza Relatório

0

localStorage.setItem() saves information as Strings which is why you see "[Object][Object]" being saved since that is what it is receiving.

So you need to transform your object to a String before you save it.

You can achieve this by using the JSON.stringify() function.

Note: you will have to transform the String back to an object when you need to get it. You can achieve this by using the JSON.parse()

Example:

localStorage.setItem('username', JSON.stringify(userState.username))
localStorage.setItem('token', JSON.stringify(token))

JSON.parse(localStorage.getItem('username'))
JSON.parse(localStorage.getItem('token'))
about 4 years ago · Juan Pablo Isaza Relatório

0

axios promise returns response object which has a data attribute. To access token you should call res.data and store it like so localStorage.setItem('token',res.data)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda